package lt.marsrutai.mobile.android.adapter;

import java.util.ArrayList;
import java.util.List;

import lt.marsrutai.mobile.android.util.StringUtils;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

/**
 * Adapter for displaying tabbed content. Contains {@link TabInfoProvider tab
 * information providers} representing hosted tabs.
 * 
 * @author Justas
 */
public class TabAdapter extends FragmentStatePagerAdapter {

    private List<TabInfoProvider> tabs = new ArrayList<TabInfoProvider>();

    public TabAdapter(FragmentManager fm) {
        super(fm);
    }

    /**
     * Add a tab to the adapter.
     * 
     * @param tabInfo
     */
    public void addTab(TabInfoProvider tabInfo) {
        tabs.add(tabInfo);
        notifyDataSetChanged();
    }

    @Override
    public Fragment getItem(int position) {
        TabInfoProvider tab = tabs.get(position);
        
        Fragment fragment = null;
        try {
            fragment = tab.getFragmentClass().newInstance();
        }
        catch (InstantiationException e) {
            throw new Fragment.InstantiationException("Failed to instantiate fragment.", e);
        }
        catch (IllegalAccessException e) {
            throw new Fragment.InstantiationException("Failed to instantiate fragment.", e);
        }
        
        fragment.setArguments(tabs.get(position).getBundle());
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return StringUtils.capitalize(tabs.get(position).getTitle());
    }

    @Override
    public int getCount() {
        return tabs.size();
    }
}